﻿Imports System.Text
Imports System.IO.Ports
Public Class Frm_SYSReportDefine
    Implements IDServer.IDServer.IDServer

    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
    Private WithEvents MainForm As Frm_MainForm

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

#Region "  Events "

    Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim SQL As String = String.Empty
        SQL += "select  ListCode,ModeName+' ('+ListCode+')' as ModeName from BSC_OtherDefineB a" + vbNewLine
        SQL += "inner join BSC_OtherDefineA b on a.ItemNO=b.id" + vbNewLine
        SQL += "inner join Sys_ModeDefine c on ListCode=ModeNo and b.ItemCode='ReportPath'" + vbNewLine
        SQL += "where c.parentid=0" + vbNewLine
        SQL += "union" + vbNewLine
        SQL += "select '' as ListCode ,'' as ModeName" + vbNewLine



        Me.cbxModelName.DisplayMember = "ModeName"
        Me.cbxModelName.ValueMember = "listcode"
        Dim tb As DataTable = App.ReturnDataTable(SQL)
        Me.cbxModelName.DataSource = tb
        Me.cbxModelName1.DisplayMember = "ModeName"
        Me.cbxModelName1.ValueMember = "listcode"
        Me.cbxModelName1.DataSource = tb.Copy
        Me.cbxModelName1.SelectedIndex = -1
        SQL = "select b.ListB from BSC_otherDefineB b " + vbNewLine
        SQL += "inner join BSC_otherDefineA a" + vbNewLine
        SQL += "on b.itemNO=a.[id]" + vbNewLine
        SQL += " where a.itemcode='RepParmDefine' and b.listA='ShowEnum'" + vbNewLine
        cbxParamDisplayType.DisplayMember = "ListB"
        cbxParamDisplayType.ValueMember = "ListB"
        cbxParamDisplayType.DataSource = App.ReturnDataTable(SQL)


        Dim tbEnum As New DataTable
        tbEnum.Columns.Add("Name")
        tbEnum.Columns.Add("Value", GetType(E_ReportConstDefine))

        For Each item As String In System.Enum.GetNames(GetType(E_ReportConstDefine))
            Dim row As DataRow = tbEnum.NewRow
            row("Name") = item
            row("Value") = System.Enum.Parse(GetType(E_ReportConstDefine), item)
            tbEnum.Rows.Add(row)
        Next
        tbEnum.AcceptChanges()
        cbxRptDefineValue.DisplayMember = "Name"
        cbxRptDefineValue.ValueMember = "Value"
        cbxRptDefineValue.DataSource = tbEnum
        cbxRptDefineValue.SelectedIndex = -1

        AddControlEvent()
        PrepareDGV()

    End Sub

    Private Sub tbxWhereExpCount_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbxWhereExpCount.TextChanged
        cbxItemNoInParent_DataBind()
    End Sub

    Private Sub tbxID_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbxID.TextChanged
        Me.btnPreview.Enabled = Not isNull(tbxID.Text)
    End Sub

    Private Sub ClickToShowToolTip(ByVal useControl As System.Object, ByVal e As System.EventArgs)
        ShowToolTip(useControl)
    End Sub

#Region " Button Events "
    Private Sub btnFinish_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFinish.Click
        If Me.btnHelp.Tag = True Then
            Exit Sub
        End If
        Dim strParentID As String = String.Empty
        strParentID = Me.tbxID.Text.Trim()
        If Me.cbxModelName.SelectedIndex = -1 Then
            If Msg.MsgYesNo(My.Resources.Fillcorrectmodulename) = DialogResult.No Then
                Exit Sub
            End If
        End If

        Dim strmsg As String = ""
        If isNull(strParentID) Then
            strmsg = My.Resources.Confirmaddrecord
        Else
            strmsg = My.Resources.Confirmsaverecord
        End If

        If Msg.MsgYesNo(strmsg, "") = DialogResult.No Then
            Exit Sub
        End If


        Dim dtt As New DataTable
        Dim tran As SqlClient.SqlTransaction
        Try
            Dim sqlcmd As New SqlClient.SqlCommand()
            Dim cnn As SqlClient.SqlConnection = App.GetConn
            If cnn Is Nothing Then
                Exit Sub
            End If
            tran = cnn.BeginTransaction()
            With sqlcmd
                .CommandText = "select max(ID)+1 as ID from dbo.ReportCfgMaster"
                .Connection = cnn
                .Transaction = tran
                .CommandType = CommandType.Text
            End With

            Dim MID As Object

            If isNull(strParentID) Then
                MID = sqlcmd.ExecuteScalar()

                sqlcmd.Parameters.Clear()

                Dim SQL As String = String.Empty
                SQL += "INSERT INTO [ReportCfgMaster]" + vbNewLine
                SQL += "([ID]" + vbNewLine
                SQL += ",[ModelName]" + vbNewLine
                SQL += ",[ReportDisName]" + vbNewLine
                SQL += ",[ReportFile]" + vbNewLine
                SQL += ",[SQLScript]" + vbNewLine
                SQL += ",[SQLExpItemCount])" + vbNewLine
                SQL += "VALUES" + vbNewLine
                SQL += "(@ID,@ModelName, @ReportDisName, @ReportFile" + vbNewLine
                SQL += ",@SQLScript,@SQLExpItemCount)" + vbNewLine
                sqlcmd.CommandText = SQL

                sqlcmd.Parameters.Add("@ID", SqlDbType.BigInt)
                sqlcmd.Parameters.Add("@ModelName", SqlDbType.NVarChar)
                sqlcmd.Parameters.Add("@ReportDisName", SqlDbType.NVarChar)
                sqlcmd.Parameters.Add("@ReportFile", SqlDbType.NVarChar)
                sqlcmd.Parameters.Add("@SQLScript", SqlDbType.NVarChar)
                sqlcmd.Parameters.Add("@SQLExpItemCount", SqlDbType.SmallInt)
                For Each parm As SqlClient.SqlParameter In sqlcmd.Parameters
                    If parm.ParameterName.Equals("@ID") Then
                        parm.Value = MID.ToString
                    ElseIf parm.ParameterName.Equals("@ModelName") Then
                        parm.Value = Me.cbxModelName.SelectedValue.ToString
                    ElseIf parm.ParameterName.Equals("@ReportDisName") Then
                        parm.Value = Me.tbxReportDisName.Text.Trim
                    ElseIf parm.ParameterName.Equals("@ReportFile") Then
                        parm.Value = Me.tbxReportFile.Text
                    ElseIf parm.ParameterName.Equals("@SQLScript") Then
                        parm.Value = Me.tbxSQL.Text.Trim
                    ElseIf parm.ParameterName.Equals("@SQLExpItemCount") Then
                        parm.Value = Me.tbxWhereExpCount.Text
                    End If
                Next
                sqlcmd.ExecuteNonQuery()

                Dim SQL1 As String = String.Empty
                SQL1 += "SELECT a.[ID],b.ModeName as [ModelName],[ReportDisName],[ReportFile],[SQLScript],[SQLExpItemCount]" + vbNewLine
                SQL1 += "FROM [ReportCfgMaster] a" + vbNewLine
                SQL1 += "left join Sys_ModeDefine b on a.ModelName=b. ModeNo" + vbNewLine
                SQL1 += "where 1=1 and  a.ID='" + MID.ToString + "' " + vbNewLine

                sqlcmd.CommandText = SQL1
                Dim rd As SqlClient.SqlDataReader = sqlcmd.ExecuteReader()
                dtt.Load(rd)
                dtt.TableName = "Add"
                dtt.AcceptChanges()
            Else
                MID = strParentID
                sqlcmd.Parameters.Clear()
                Dim SQL As String = String.Empty
                SQL += "UPDATE [ReportCfgMaster]" + vbNewLine
                SQL += "SET [ID] = @ID" + vbNewLine
                SQL += ",[ModelName] = @ModelName" + vbNewLine
                SQL += ",[ReportDisName] = @ReportDisName" + vbNewLine
                SQL += ",[ReportFile] = @ReportFile" + vbNewLine
                SQL += ",[SQLScript] = @SQLScript" + vbNewLine
                SQL += ",[SQLExpItemCount] = @SQLExpItemCount" + vbNewLine
                SQL += "WHERE  ID='" + MID.ToString + "'"
                sqlcmd.Parameters.Add("@ID", SqlDbType.BigInt)
                sqlcmd.Parameters.Add("@ModelName", SqlDbType.NVarChar)
                sqlcmd.Parameters.Add("@ReportDisName", SqlDbType.NVarChar)
                sqlcmd.Parameters.Add("@ReportFile", SqlDbType.NVarChar)
                sqlcmd.Parameters.Add("@SQLScript", SqlDbType.NVarChar)
                sqlcmd.Parameters.Add("@SQLExpItemCount", SqlDbType.SmallInt)
                For Each parm As SqlClient.SqlParameter In sqlcmd.Parameters
                    If parm.ParameterName.Equals("@ID") Then
                        parm.Value = MID.ToString
                    ElseIf parm.ParameterName.Equals("@ModelName") Then
                        parm.Value = Me.cbxModelName.SelectedValue.ToString
                    ElseIf parm.ParameterName.Equals("@ReportDisName") Then
                        parm.Value = Me.tbxReportDisName.Text.Trim
                    ElseIf parm.ParameterName.Equals("@ReportFile") Then
                        parm.Value = Me.tbxReportFile.Text.Trim
                    ElseIf parm.ParameterName.Equals("@SQLScript") Then
                        parm.Value = Me.tbxSQL.Text.Trim
                    ElseIf parm.ParameterName.Equals("@SQLExpItemCount") Then
                        parm.Value = Me.tbxWhereExpCount.Text.Trim
                    End If
                Next
                SQL += "DELETE FROM  [ReportCfgDetail] WHERE ParentID='" + MID.ToString + "'"
                sqlcmd.CommandText = SQL
                sqlcmd.ExecuteNonQuery()

                Dim SQL1 As String = String.Empty
                SQL1 += "SELECT a.[ID],b.ModeName as [ModelName],[ReportDisName],[ReportFile],[SQLScript],[SQLExpItemCount]" + vbNewLine
                SQL1 += "FROM [ReportCfgMaster] a" + vbNewLine
                SQL1 += "left join Sys_ModeDefine b on a.ModelName=b. ModeNo" + vbNewLine
                SQL1 += "where 1=1 and  a.ID='" + MID.ToString + "' " + vbNewLine

                sqlcmd.CommandText = SQL1
                Dim rd As SqlClient.SqlDataReader = sqlcmd.ExecuteReader()
                dtt.Load(rd)
                dtt.TableName = "Update"
                dtt.AcceptChanges()
            End If

            Dim dt As DataTable
            dt = CType(Me.dgv_Params.DataSource, DataTable)
            dt = dt.Copy()
            dt.Columns.Remove("ID")
            dt.AcceptChanges()
            dt.Columns.Add("ID", GetType(Int64))
            dt.Columns("ID").SetOrdinal(0)
            dt.AcceptChanges()

            For Each row As DataRow In dt.Rows
                row("ParentID") = MID
            Next

            Dim sqlb As New SqlClient.SqlBulkCopy(cnn, SqlClient.SqlBulkCopyOptions.Default, tran)
            sqlb.BulkCopyTimeout = 100
            sqlb.DestinationTableName = "ReportCfgDetail"
            sqlb.WriteToServer(dt)
            If dtt.Columns.Count > 0 And dtt.TableName = "Add" Then
                InsertToDGV(Me.dgv_master, dtt)
            ElseIf dtt.Columns.Count > 0 And dtt.TableName = "Update" Then
                UpdateDGV(Me.dgv_master, dtt, "ID")
            End If
            tran.Commit()
            Me.tbxID.Text = MID.ToString
            Msg.MsgOK("保存成功")
        Catch ex As Exception
            If tran Is Nothing Then
                Msg.MsgError("btnFinish_Click 未知的錯誤: " + ex.Message)
                Exit Sub
            End If
            tran.Rollback()
            Msg.MsgError("btnFinish_Click 錯誤: " + ex.Message)
        End Try
    End Sub

    Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
        Try
            If Me.btnHelp.Tag = True Then
                Exit Sub
            End If
            If Not textIsInt(Me.tbxWhereExpCount) Then
                MessageBox.Show("錯誤")
                Exit Sub
            End If
            Dim lis As New List(Of String)
            Dim count As Int32 = Convert.ToInt32(Me.tbxWhereExpCount.Text)
            For i As Int32 = 0 To count - 1
                lis.Add(" ")
            Next
            Dim dt As DataTable = CType(Me.dgv_Params.DataSource, DataTable)
            If dt Is Nothing Then
                MessageBox.Show("錯誤")
                Exit Sub
            End If

            Dim itemcount As Int32 = 0

            If dt.Rows.Count > 0 Then
                itemcount = dt.Compute("max(ItemNoInParent)", "1=1")
            End If
            For index As Integer = 0 To itemcount
                Dim rows() As DataRow = dt.Select("ItemNoInParent=" + index.ToString)
                If rows.Length > 0 Then
                    For index1 As Integer = 0 To rows.Length - 1
                        lis(index) = lis(index) + ParamFormatTest(rows(index1))
                    Next
                End If
            Next

            Dim strsql As String = String.Format(Me.tbxSQL.Text, lis.ToArray())
            MessageBox.Show(strsql)
            My.Computer.Clipboard.Clear()
            If Not isNull(strsql) Then
                My.Computer.Clipboard.SetText(strsql)
            End If
        Catch ex As Exception
            Msg.MsgError("錯誤位於 " + Me.Name + "—— btnTest_Click：" + ex.Message)
        End Try
    End Sub

    Private Sub btnParamAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnParamAdd.Click
        If Me.btnHelp.Tag = True Then
            Exit Sub
        End If
        Dim dt As DataTable = CType(Me.dgv_Params.DataSource, DataTable)
        'dt.AcceptChanges()
        dt = dt.Copy()

        If Not dt.Columns.Contains("ReportTextObject") Then
            dt.Columns.Add("ReportTextObject")
        End If
        If Not dt.Columns.Contains("ReportTextObjContent") Then
            dt.Columns.Add("ReportTextObjContent")
        End If
        dt.AcceptChanges()
        Dim row As DataRow = dt.NewRow()
        If textIsInt(Me.tbxID) Then
            row("ParentID") = Convert.ToInt32(Me.tbxID.Text)
        End If
        row("ItemNoInParent") = Convert.ToInt32(Me.cbxItemNoInParent.SelectedValue)
        row("Param") = Me.tbxParam.Text.Trim
        row("ParamDisName") = Me.tbxParamDisName.Text.Trim
        row("ParamDisPlayType") = Me.cbxParamDisplayType.SelectedValue
        row("ParamValueProvide") = Me.tbxParamValueProvide.Text.Trim
        row("ParamSpecialFormat") = Me.tbxParamSpecialFormat.Text.Trim
        If Me.RadioButton1.Checked Then
            row("ReportTextObjContent") = Me.tbxReportTextobjContent.Text.Trim
        ElseIf Me.RadioButton2.Checked And Me.cbxRptDefineValue.SelectedIndex <> -1 Then
            row("ReportTextObjContent") = SetRptTextObjDefineContent(Convert.ToInt32(Me.cbxRptDefineValue.SelectedValue))
        End If
        row("ReportTextObject") = Me.tbxReportTextObj.Text.Trim
        dt.Rows.Add(row)
        dt.AcceptChanges()
        Me.dgv_Params.DataSource = dt
    End Sub

    Private Sub btnParamSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnParamSave.Click
        Dim cell As DataGridViewCell = Me.dgv_Params.CurrentCell
        If Not cell Is Nothing Then
            Dim index As Int32 = cell.RowIndex
            Dim row As DataGridViewRow = dgv_Params.Rows(index)
            'row.Cells("ID").Value = Convert.ToInt32(Me.tbxID.Text)
            If textIsInt(Me.tbxID) Then
                row.Cells("ParentID").Value = Convert.ToInt32(Me.tbxID.Text)
            End If
            row.Cells("ItemNoInParent").Value = Convert.ToInt32(Me.cbxItemNoInParent.SelectedValue)
            row.Cells("Param").Value = Me.tbxParam.Text.Trim
            row.Cells("ParamDisName").Value = Me.tbxParamDisName.Text.Trim
            row.Cells("ParamDisPlayType").Value = Me.cbxParamDisplayType.SelectedValue
            row.Cells("ParamValueProvide").Value = Me.tbxParamValueProvide.Text.Trim
            row.Cells("ParamSpecialFormat").Value = Me.tbxParamSpecialFormat.Text.Trim.Replace("and", " and").Replace("And", " And".Replace("AND", " AND"))
            If Me.RadioButton1.Checked Then
                row.Cells("ReportTextObjContent").Value = Me.tbxReportTextobjContent.Text.Trim
            ElseIf Me.RadioButton2.Checked And Me.cbxRptDefineValue.SelectedIndex <> -1 Then
                row.Cells("ReportTextObjContent").Value = SetRptTextObjDefineContent(Convert.ToInt32(Me.cbxRptDefineValue.SelectedValue))
            End If
            row.Cells("ReportTextObject").Value = Me.tbxReportTextObj.Text.Trim
            CType(dgv_Params.DataSource, DataTable).AcceptChanges()
        End If
    End Sub

    Private Sub btnParamDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnParamDel.Click
        Dim cell As DataGridViewCell = Me.dgv_Params.CurrentCell
        If Not cell Is Nothing Then
            dgv_Params.Rows.RemoveAt(cell.RowIndex)
            CType(dgv_Params.DataSource, DataTable).AcceptChanges()
        End If
    End Sub

    Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click
        Dim SQL As String = String.Empty
        SQL += "SELECT a.[ID],b.ModeName as [ModelName],[ReportDisName],[ReportFile],[SQLScript],[SQLExpItemCount]" + vbNewLine
        SQL += "FROM [ReportCfgMaster] a" + vbNewLine
        SQL += "left join Sys_ModeDefine b on a.ModelName=b.ModeNo" + vbNewLine
        SQL += "where 1=1" + vbNewLine

        If Me.cbxModelName1.SelectedIndex <> -1 Then
            If Not isNull(cbxModelName1.SelectedValue.ToString) Then
                SQL += "and ModelName='" + Me.cbxModelName1.SelectedValue + "'" + vbNewLine
            End If
        End If
        If Not String.IsNullOrEmpty(Me.tbxReportFile1.Text.Trim) Then
            SQL += "and ReportFile='" + Me.tbxReportFile1.Text.Trim + "'" + vbNewLine
        End If
        If Not String.IsNullOrEmpty(Me.tbxReportDisName1.Text.Trim) Then
            SQL += "and tbxReportDisName='" + Me.tbxReportDisName1.Text.Trim + "'" + vbNewLine
        End If
        Me.dgv_master.DataSource = App.ReturnDataTable(SQL)
        Me.dgv_master.Columns("SQLScript").Visible = False
        'ExportToTxtForFormload(Me.dgv_master.DataSource, Me.dgv_master, "Master", "Master.txt")
    End Sub

    Private Sub btnClear2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear2.Click
        If Me.btnHelp.Tag = True Then
            Exit Sub
        End If
        CType(dgv_Params.DataSource, DataTable).Rows.Clear()
        CType(dgv_Params.DataSource, DataTable).AcceptChanges()
        For Each col As Control In gbxParam.Controls
            If TypeOf col Is TextBox Then
                col.Text = ""
            ElseIf TypeOf col Is GroupBox Then
                For Each col1 As Control In col.Controls
                    If TypeOf col1 Is TextBox Then
                        col1.Text = ""
                    ElseIf TypeOf col1 Is ComboBox Then
                        CType(col1, ComboBox).SelectedIndex = -1
                    End If
                Next
            End If
        Next
    End Sub

    Private Sub btnClear1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear1.Click
        If Me.btnHelp.Tag = True Then
            Exit Sub
        End If
        ClearAll()
    End Sub

    Private Sub btnReportAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReportAdd.Click
        If Me.btnHelp.Tag = True Then
            Exit Sub
        End If
        Me.tbxID.Text = ""
        Me.btnFinish.PerformClick()
    End Sub


    Private Sub btnHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHelp.Click
        Me.Cursor = Cursors.Help
        Me.btnHelp.Tag = True
    End Sub


    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
        If Me.btnHelp.Tag = True Then
            Exit Sub
        End If

        If MsgYesNo(My.Resources.ConfirmDelete) = Windows.Forms.DialogResult.Yes Then
            If textIsInt(Me.tbxID) Then
                Dim mid As String = Me.tbxID.Text.Trim
                Dim Sql As String = ""
                Sql = "DELETE FROM  [ReportCfgDetail] WHERE ParentID='" + mid + "'" + vbNewLine
                Sql += "DELETE FROM  [ReportCfgMaster] WHERE ID='" + mid + "'" + vbNewLine
                Exec(Sql, E_ExecType.ExecuteNonQuery)
                Dim dgv As DataGridView = Me.dgv_master

                Dim drow As DataGridViewRow = Nothing
                For Each row As DataGridViewRow In dgv.Rows
                    If row.Cells("ID").Value.ToString.Equals(mid, StringComparison.InvariantCultureIgnoreCase) Then
                        drow = row
                    End If
                Next

                If Not drow Is Nothing Then
                    dgv.Rows.Remove(drow)
                End If
            Else
                ClearAll()
            End If
        End If
    End Sub
    Private Sub btnPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreview.Click
        Try
            If Me.btnHelp.Tag = True Then
                Exit Sub
            End If
            If Not Me.textIsInt(Me.tbxID) Then
                Msg.MsgOK(My.Resources.NoFindReport)
                Exit Sub
            End If
            Dim frm As New Frm_ReportSearch(Me.tbxID.Text)
            frm.StartPosition = FormStartPosition.CenterParent
            frm.ShowDialog()
        Catch ex As Exception
            Msg.MsgError(Me.Name + "—btnPreview_Click：" + ex.Message)
        End Try
    End Sub

#End Region

#Region " DataGridView Events "

    Private Sub dgv_master_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv_master.CellDoubleClick
        Dim dgv As DataGridView = sender
        If e.ColumnIndex = -1 Or e.RowIndex = -1 Then
            Exit Sub
        End If
        Dim drow As DataGridViewRow = dgv.Rows(e.RowIndex)
        If Not drow.IsNewRow Then
            Me.tbxID.Text = drow.Cells("ID").Value.ToString
            Me.cbxModelName.SelectedIndex = Me.cbxModelName.FindString(drow.Cells("ModelName").Value.ToString)
            Me.tbxWhereExpCount.Text = drow.Cells("SQLExpItemCount").Value.ToString
            Me.tbxSQL.Text = drow.Cells("SQLScript").Value.ToString
            Me.tbxReportFile.Text = drow.Cells("ReportFile").Value.ToString
            Me.tbxReportDisName.Text = drow.Cells("ReportDisName").Value.ToString
            Me.TabControl1.SelectedIndex = 1
            Dim SQL As String = String.Empty
            SQL += "SELECT [ID]" + vbNewLine
            SQL += ",[ParentID]" + vbNewLine
            SQL += ",[ItemNoInParent]" + vbNewLine
            SQL += ",[Param]" + vbNewLine
            SQL += ",[ParamDisName]" + vbNewLine
            SQL += ",[ParamDisPlayType]" + vbNewLine
            SQL += ",ParamValueProvide=isnull([ParamValueProvide],'')" + vbNewLine
            SQL += ",ParamSpecialFormat=isnull([ParamSpecialFormat],'')" + vbNewLine
            SQL += ",ReportTextObject=isnull([ReportTextObject],'')" + vbNewLine
            SQL += ",ReportTextObjContent=isnull([ReportTextObjContent],'')" + vbNewLine
            SQL += "FROM [ReportCfgDetail] " + vbNewLine
            SQL += "Where 1=1 and ParentID='" + drow.Cells("ID").Value.ToString + "'" + vbNewLine
            Dim dt As DataTable = App.ReturnDataTable(SQL)
            Me.dgv_Params.DataSource = dt
            'App.ExportToTxtForFormload(dt, Me.dgv_Params, "paramTab", "paramTab.txt")
        End If
    End Sub

    Private Sub dgv_Params_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv_Params.CellClick
        Dim dgv As DataGridView = sender
        If e.ColumnIndex = -1 Or e.RowIndex = -1 Then
            Exit Sub
        End If
        Dim drow As DataGridViewRow = dgv.Rows(e.RowIndex)
        Me.tbxParam.Text = drow.Cells("Param").Value.ToString
        Me.tbxParentId.Text = drow.Cells("ParentID").Value.ToString()
        Me.tbxParamId.Text = drow.Cells("ID").Value.ToString()
        Me.cbxItemNoInParent.SelectedIndex = Me.cbxItemNoInParent.FindString(drow.Cells("ItemNoInParent").Value.ToString())
        Me.tbxParamDisName.Text = drow.Cells("ParamDisName").Value.ToString()
        Me.cbxParamDisplayType.SelectedIndex = Me.cbxParamDisplayType.FindString(drow.Cells("ParamDisPlayType").Value.ToString())
        Me.tbxParamValueProvide.Text = drow.Cells("ParamValueProvide").Value.ToString()
        Me.tbxParamSpecialFormat.Text = drow.Cells("ParamSpecialFormat").Value.ToString()

        If ModSys.IsTextObjADefineValue(drow.Cells("ReportTextObjContent").Value.ToString) Then
            Me.tbxReportTextObj.Text = drow.Cells("ReportTextObject").Value.ToString
            Me.RadioButton2.Checked = True
            Dim ReportTextObjContent As String = ModSys.GetRptTextObjDefineContent(drow.Cells("ReportTextObjContent").Value.ToString)
            Me.cbxRptDefineValue.SelectedIndex = Me.cbxRptDefineValue.FindString(ReportTextObjContent)
            Me.tbxReportTextobjContent.Text = ""
        Else
            Me.RadioButton1.Checked = True
            Me.tbxReportTextObj.Text = drow.Cells("ReportTextObject").Value.ToString
            Me.tbxReportTextobjContent.Text = drow.Cells("ReportTextObjContent").Value.ToString
            Me.cbxRptDefineValue.SelectedIndex = -1
        End If
    End Sub

    Private Sub dgv_Params_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgv_Params.CurrentCellChanged
        Dim dgv As DataGridView = sender
        Dim cell As DataGridViewCell = dgv.CurrentCell
        If cell Is Nothing Then
            Exit Sub
        End If
        Dim drow As DataGridViewRow = dgv.Rows(cell.RowIndex)
        If drow.IsNewRow Then
            Exit Sub
        End If
        Me.tbxParam.Text = drow.Cells("Param").Value.ToString
        Me.tbxParentId.Text = drow.Cells("ParentID").Value.ToString()
        Me.tbxParamId.Text = drow.Cells("ID").Value.ToString()
        Me.cbxItemNoInParent.SelectedIndex = Me.cbxItemNoInParent.FindString(drow.Cells("ItemNoInParent").Value.ToString())
        Me.tbxParamDisName.Text = drow.Cells("ParamDisName").Value.ToString()
        Me.cbxParamDisplayType.SelectedIndex = Me.cbxParamDisplayType.FindString(drow.Cells("ParamDisPlayType").Value.ToString())
        Me.tbxParamValueProvide.Text = drow.Cells("ParamValueProvide").Value.ToString()
        Me.tbxParamSpecialFormat.Text = drow.Cells("ParamSpecialFormat").Value.ToString()
        If ModSys.IsTextObjADefineValue(drow.Cells("ReportTextObjContent").Value.ToString) Then
            Me.tbxReportTextObj.Text = drow.Cells("ReportTextObject").Value.ToString
            Me.RadioButton2.Checked = True
            Dim ReportTextObjContent As String = ModSys.GetRptTextObjDefineContent(drow.Cells("ReportTextObjContent").Value.ToString)
            Me.cbxRptDefineValue.SelectedIndex = Me.cbxRptDefineValue.FindString(ReportTextObjContent)
            Me.tbxReportTextobjContent.Text = ""
        Else
            Me.RadioButton1.Checked = True
            Me.tbxReportTextObj.Text = drow.Cells("ReportTextObject").Value.ToString
            Me.tbxReportTextobjContent.Text = drow.Cells("ReportTextObjContent").Value.ToString
            Me.cbxRptDefineValue.SelectedIndex = -1
        End If
    End Sub

    Private Sub dgv_master_RowsRemoved(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles dgv_master.RowsRemoved
        Dim dgv As DataGridView
        dgv = sender
        If dgv.CurrentCell Is Nothing Then
            Exit Sub
        ElseIf dgv.CurrentCell.RowIndex <> -1 Then
            Dim drow As DataGridViewRow = dgv.Rows(dgv.CurrentCell.RowIndex)
            If Not drow.IsNewRow Then
                Me.tbxID.Text = drow.Cells("ID").Value.ToString
                Me.cbxModelName.SelectedIndex = Me.cbxModelName.FindString(drow.Cells("ModelName").Value.ToString)
                Me.tbxWhereExpCount.Text = drow.Cells("SQLExpItemCount").Value.ToString
                Me.tbxSQL.Text = drow.Cells("SQLScript").Value.ToString
                Me.tbxReportFile.Text = drow.Cells("ReportFile").Value.ToString
                Me.tbxReportDisName.Text = drow.Cells("ReportDisName").Value.ToString
                Dim SQL As String = String.Empty
                SQL += "SELECT [ID]" + vbNewLine
                SQL += ",[ParentID]" + vbNewLine
                SQL += ",[ItemNoInParent]" + vbNewLine
                SQL += ",[Param]" + vbNewLine
                SQL += ",[ParamDisName]" + vbNewLine
                SQL += ",[ParamDisPlayType]" + vbNewLine
                SQL += ",ParamValueProvide=isnull([ParamValueProvide],'')" + vbNewLine
                SQL += ",ParamSpecialFormat=isnull([ParamSpecialFormat],'')" + vbNewLine
                SQL += ",ReportTextObject=isnull([ReportTextObject],'')" + vbNewLine
                SQL += ",ReportTextObjContent=isnull([ReportTextObjContent],'')" + vbNewLine
                SQL += "FROM [ReportCfgDetail] " + vbNewLine
                SQL += "Where 1=1 and ParentID='" + drow.Cells("ID").Value.ToString + "'" + vbNewLine
                Dim dt As DataTable = App.ReturnDataTable(SQL)
                Me.dgv_Params.DataSource = dt
            Else
                Dim SQL As String = String.Empty
                SQL += "SELECT [ID]" + vbNewLine
                SQL += ",[ParentID]" + vbNewLine
                SQL += ",[ItemNoInParent]" + vbNewLine
                SQL += ",[Param]" + vbNewLine
                SQL += ",[ParamDisName]" + vbNewLine
                SQL += ",[ParamDisPlayType]" + vbNewLine
                SQL += ",ParamValueProvide=isnull([ParamValueProvide],'')" + vbNewLine
                SQL += ",ParamSpecialFormat=isnull([ParamSpecialFormat],'')" + vbNewLine
                SQL += ",ReportTextObject=isnull([ReportTextObject],'')" + vbNewLine
                SQL += ",ReportTextObjContent=isnull([ReportTextObjContent],'')" + vbNewLine
                SQL += "FROM [ReportCfgDetail] " + vbNewLine
                SQL += "Where 1<>1 " + vbNewLine
                Dim dt As DataTable = App.ReturnDataTable(SQL)
                Me.dgv_Params.DataSource = dt
            End If
        End If
    End Sub

#End Region



#End Region

#Region " Private Methods "

    Private Function textIsInt(ByVal sender As TextBox) As Boolean
        Dim succed As Boolean = True
        Dim tbx As TextBox = sender
        Dim str As String = tbx.Text.Trim
        If str.EndsWith("..") Then
            tbx.Text = ""
            succed = False
        ElseIf str.EndsWith(".") Then
            succed = False
        Else
            Dim i As Int64
            If Not Int64.TryParse(str, i) Then
                tbx.Text = ""
                succed = False
            End If
        End If
        Return succed
    End Function

    Private Sub cbxItemNoInParent_DataBind()
        Try
            Dim tb As New DataTable()
            tb.Columns.Add("Value")
            tb.AcceptChanges()
            If Not textIsInt(Me.tbxWhereExpCount) Then
                cbxItemNoInParent.DataSource = Nothing
                Me.tbxWhereExpCount.Focus()
                Exit Sub
            End If
            For index As Integer = -1 To Convert.ToInt32(Me.tbxWhereExpCount.Text.Trim) - 1
                Dim row As DataRow = tb.NewRow
                row(0) = index
                tb.Rows.Add(row)
            Next
            tb.AcceptChanges()
            cbxItemNoInParent.DisplayMember = "Value"
            cbxItemNoInParent.ValueMember = "Value"
            cbxItemNoInParent.DataSource = tb
        Catch ex As Exception
            Msg.MsgError("錯誤位於：" + Me.Name + "——cbxItemNoInParent_DataBind：" + vbNewLine + ex.Message)
        End Try
    End Sub

    Private Function ParamFormatTest(ByVal row As DataRow) As String
        Dim str As String = String.Empty
        Dim paramformatindex As Int32 = 0
        If row.Table.Columns.Contains("ParamSpecialFormat") And row.Table.Columns.Contains("ParamDisPlayType") And row.Table.Columns.Contains("Param") Then
            Dim ParamDisType As ShowEnum = System.Enum.Parse(GetType(ShowEnum), row("ParamDisPlayType").ToString)
            paramformatindex = row.Table.Columns("ParamSpecialFormat").Ordinal
            Dim paramformat As String = row(paramformatindex).ToString
            If Not isNull(paramformat) Then
                Select Case ParamDisType
                    Case ShowEnum.GbxRdbArray, ShowEnum.GbxRdbSQL
                        str = String.Format(paramformat, FOperator(E_Operator.包含), formatvalue(E_Operator.包含, "value"))
                    Case ShowEnum.NotSet
                        str = ""
                    Case ShowEnum.PanelData, ShowEnum.PanelStr
                        str = String.Format(paramformat, FOperator(E_Operator.包含), formatvalue(E_Operator.包含, "value"))
                    Case ShowEnum.PanelDataMultiSelect, ShowEnum.PanelMultiInput
                        str = String.Format(paramformat, FOperator(E_Operator.在集合中), formatvalue(E_Operator.在集合中, "A,B"))
                    Case ShowEnum.PanelRemark
                        str = String.Format(paramformat, FOperator(E_Operator.等於), formatvalue(E_Operator.等於, "Remark Text"))
                    Case ShowEnum.PanelDateTime
                        str = String.Format(paramformat, Now.ToString("yyyy-MM-dd"), Now.ToString("yyyy-MM-dd"))
                    Case ShowEnum.PanelNumeric
                        str = String.Format(paramformat, "1", "2")
                    Case ShowEnum.OrderByOrGroup
                        str = paramformat
                End Select
            Else
                Select Case ParamDisType
                    Case ShowEnum.GbxRdbArray, ShowEnum.GbxRdbSQL
                        str = String.Format(formatStr(E_Operator.包含), row("Param").ToString, "value")
                    Case ShowEnum.PanelDataMultiSelect, ShowEnum.PanelMultiInput
                        str = String.Format(formatStr(E_Operator.在集合中), formatvalue(E_Operator.在集合中, "A,B"))
                    Case ShowEnum.NotSet
                        str = ""
                    Case ShowEnum.PanelData, ShowEnum.PanelStr
                        str = String.Format(formatStr(E_Operator.包含), row("Param").ToString, "value")
                    Case ShowEnum.PanelDateTime
                        str = String.Format(formatStr(E_Operator.從至), row("Param").ToString, Now.ToString("yyyy-MM-dd"), Now.ToString("yyyy-MM-dd"))
                    Case ShowEnum.PanelNumeric
                        str = String.Format(formatStr(E_Operator.從至), row("Param").ToString, "1", "2")
                    Case ShowEnum.OrderByOrGroup
                        str = paramformat
                End Select
            End If
        End If
        Return str
    End Function

    Private Sub ClearAll()
        For Each col As Control In gbxReport.Controls
            If TypeOf col Is TextBox Then
                col.Text = ""
            End If
        Next
        For Each col As Control In gbxParam.Controls
            If TypeOf col Is TextBox Then
                col.Text = ""
            ElseIf TypeOf col Is GroupBox Then
                For Each col1 As Control In col.Controls
                    If TypeOf col1 Is TextBox Then
                        col1.Text = ""
                    ElseIf TypeOf col1 Is ComboBox Then
                        CType(col1, ComboBox).SelectedIndex = -1
                    End If
                Next
            End If
        Next
        Dim dt As DataTable = CType(Me.dgv_Params.DataSource, DataTable)
        If Not dt Is Nothing Then
            dt = dt.Copy
            dt.Rows.Clear()
            dt.AcceptChanges()
        End If
        Me.dgv_Params.DataSource = dt
    End Sub

    Private Sub PrepareDGV()
        Try
            Dim Master As New DataTable
            Master.Columns.Add("ID", GetType(Int64))
            Master.Columns.Add("ModelName", GetType(String))
            Master.Columns.Add("ReportDisName", GetType(String))
            Master.Columns.Add("ReportFile", GetType(String))
            Master.Columns.Add("SQLScript", GetType(String))
            Master.Columns.Add("SQLExpItemCount", GetType(Int16))
            Master.AcceptChanges()
            dgv_master.DataSource = Master
            Dim caption As String = "編號^ID&模塊名^ModelName&報表名字^ReportDisName&報表文件^ReportFile&報表SQL語句^SQLScript&待傳SQL子句數^SQLExpItemCount"
            BindGridCaption(dgv_master, BindHashTable(caption))
            If dgv_master.Columns.Contains("SQLScript") Then
                dgv_master.Columns("SQLScript").Visible = False
            End If

            Dim paramTab As New DataTable
            paramTab.Columns.Add("ID", GetType(Int64))
            paramTab.Columns.Add("ParentID", GetType(Int64))
            paramTab.Columns.Add("ItemNoInParent", GetType(Int16))
            paramTab.Columns.Add("Param", GetType(String))
            paramTab.Columns.Add("ParamDisName", GetType(String))
            paramTab.Columns.Add("ParamDisPlayType", GetType(String))
            paramTab.Columns.Add("ParamValueProvide", GetType(String))
            paramTab.Columns.Add("ParamSpecialFormat", GetType(String))
            paramTab.Columns.Add("ReportTextObject", GetType(String))
            paramTab.Columns.Add("ReportTextObjContent", GetType(String))
            paramTab.AcceptChanges()
            dgv_Params.DataSource = paramTab
            Dim caption1 As String = "項目編號^ID&報表編號^ParentID&SQL中項序號^ItemNoInParent&參數名^Param&參數顯示名^ParamDisName&參數顯示類型^ParamDisPlayType&參數值來源^ParamValueProvide&參數特定格式^ParamSpecialFormat&報表TextObject^ReportTextObject&TextObject顯示^ReportTextObjContent"
            BindGridCaption(dgv_Params, BindHashTable(caption1))
            If Me.dgv_Params.Columns.Contains("ID") Then
                Me.dgv_Params.Columns("ID").Visible = False
            End If
            If Me.dgv_Params.Columns.Contains("ParentID") Then
                Me.dgv_Params.Columns("ParentID").Visible = False
            End If
        Catch ex As Exception
            Msg.MsgError(Me.Name + "—PrepareDGV：" + ex.Message)
        End Try
    End Sub

    Private Sub ShowToolTip(ByVal useControl As Control)
        '顯示的毫秒數
        Dim duration As Int32 = 500
        If Me.btnHelp.Tag = True Then
            Dim tooltext As String = Me.ToolTip1.GetToolTip(useControl)
            Select Case tooltext.Length
                Case 0 To 30
                    duration = 1500
                Case 30 To 60
                    duration = 3000
                Case 60 To 150
                    duration = 6000
                Case Else
                    duration = 8000
            End Select
            Me.ToolTip1.Show(Me.ToolTip1.GetToolTip(useControl), useControl, duration)
            Me.btnHelp.Tag = False
            Me.Cursor = Cursors.Default
        End If
    End Sub

    ''' <summary>
    ''' 給控件添加顯示ToolTip的事件
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AddControlEvent()
        AddHandler btnDel.Click, AddressOf ClickToShowToolTip
        AddHandler btnFinish.Click, AddressOf ClickToShowToolTip
        AddHandler btnParamAdd.Click, AddressOf ClickToShowToolTip
        AddHandler btnParamDel.Click, AddressOf ClickToShowToolTip
        AddHandler btnParamSave.Click, AddressOf ClickToShowToolTip
        AddHandler btnPreview.Click, AddressOf ClickToShowToolTip
        AddHandler btnReportAdd.Click, AddressOf ClickToShowToolTip
        AddHandler btnSelect.Click, AddressOf ClickToShowToolTip
        AddHandler btnTest.Click, AddressOf ClickToShowToolTip
        AddHandler cbxItemNoInParent.Click, AddressOf ClickToShowToolTip
        AddHandler cbxModelName.Click, AddressOf ClickToShowToolTip
        AddHandler cbxModelName1.Click, AddressOf ClickToShowToolTip
        AddHandler cbxParamDisplayType.Click, AddressOf ClickToShowToolTip
        AddHandler tbxID.Click, AddressOf ClickToShowToolTip
        AddHandler tbxParam.Click, AddressOf ClickToShowToolTip
        AddHandler tbxParamDisName.Click, AddressOf ClickToShowToolTip
        AddHandler tbxParamId.Click, AddressOf ClickToShowToolTip
        AddHandler tbxParamSpecialFormat.Click, AddressOf ClickToShowToolTip
        AddHandler tbxParamValueProvide.Click, AddressOf ClickToShowToolTip
        AddHandler tbxParentId.Click, AddressOf ClickToShowToolTip
        AddHandler tbxReportDisName.Click, AddressOf ClickToShowToolTip
        AddHandler tbxReportDisName1.Click, AddressOf ClickToShowToolTip
        AddHandler tbxReportFile.Click, AddressOf ClickToShowToolTip
        AddHandler tbxReportFile1.Click, AddressOf ClickToShowToolTip
        AddHandler tbxReportTextObj.Click, AddressOf ClickToShowToolTip
        AddHandler tbxReportTextobjContent.Click, AddressOf ClickToShowToolTip
        AddHandler tbxSQL.Click, AddressOf ClickToShowToolTip
        AddHandler tbxWhereExpCount.Click, AddressOf ClickToShowToolTip
    End Sub

#End Region

#Region " InterFace Methods "
    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd

    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave

    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

#End Region

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim frm As New ReportFindTool()
        frm.Show()
    End Sub

    Private Sub gbxReport_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gbxReport.Enter

    End Sub
End Class